﻿using HelloOne.NewsSvc.Models;
using HelloOne.NewsSvc.ViewModels;
using System.Collections.Generic;
using System.Linq;

namespace HelloOne.NewsSvc.Services
{
    public class CategoryService
    {
        #region 层级结构的Category树
        /// <summary>
        /// 层级结构的Category
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public List<CategoryTreeModel> HierarchyTree(IEnumerable<Category> list)
        {
            //顶级栏目
            var topParentCategory = list.OrderByDescending(x => x.Sort)
                .OrderBy(x => x.CreatedDate)
                .Where(x => x.ParentID == null)
                .Select(x => new CategoryTreeModel { Category = x }).ToList();

            foreach (var item in topParentCategory)
            {
                HierarchyChildTree(item, list);
            }
            return topParentCategory;
        }
        private void HierarchyChildTree(CategoryTreeModel model, IEnumerable<Category> list)
        {
            var childs = list.Where(x => x.ParentID == model.Category.ID).Select(x => new CategoryTreeModel { Category = x }).ToList();
            if (childs != null)
            {
                model.Childs = childs;
                foreach (var item in childs)
                {
                    HierarchyChildTree(item, list);
                }
            }
        }
        #endregion
        #region 平等结构的Category树
        /// <summary>
        /// 平行结构的Category
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public List<Category> ParallelTree(IEnumerable<Category> list)
        {
            var tree = HierarchyTree(list);
            var slis = new List<Category>();
            string split = "╟";// "├";
            foreach (var item in tree)
            {
                item.Category.Name = $"{split} {item.Category.Name}";
                slis.Add(item.Category);
                ParallelChildTree(slis, item, list, split);
            }

            return slis;
        }

        private void ParallelChildTree(List<Category> slis, CategoryTreeModel treeModel, IEnumerable<Category> list, string split)
        {
            split = split + "───";
            foreach (var item in treeModel.Childs)
            {
                item.Category.Name = $"{split} {item.Category.Name}";
                slis.Add(item.Category);
                ParallelChildTree(slis, item, list, split);
            }
        }
        #endregion
    }

 
}
